package com.itheima.advice;

import com.github.pagehelper.Page;
import com.itheima.mapper.EmpLoginlogMapper;
import com.itheima.pojo.EmpDto;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.LoginInfo;
import com.itheima.utils.TliasException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@Slf4j
//@Aspect
public class RecordEmpLoginAdvice {

    @Autowired
    private EmpLoginlogMapper empLoginlogMapper;

    @Around("execution(* com.itheima.service.impl.EmpServiceImpl.login(..))")
    public  Object loginAdvice(ProceedingJoinPoint pjp) throws Throwable{
        Object[] args = pjp.getArgs();
        EmpDto empDto = (EmpDto)args[0];
        EmpLoginLog empLoginLog = new EmpLoginLog();
        empLoginLog.setUsername(empDto.getUsername());
        empLoginLog.setPassword(empDto.getPassword());
        empLoginLog.setLoginTime(LocalDateTime.now());

        long begin =System.currentTimeMillis();

        long end = 0;

        Object result = null;
        try {
             result = pjp.proceed();
            end = System.currentTimeMillis();

            empLoginLog.setIsSuccess((short)1);
            LoginInfo loginInfo = (LoginInfo)result;
            empLoginLog.setJwt(loginInfo.getToken());
            empLoginLog.setCostTime(end-begin);
            empLoginlogMapper.save(empLoginLog);
            return result;
        } catch (Throwable e) {

            end = System.currentTimeMillis();
            empLoginLog.setIsSuccess((short)0);
            empLoginLog.setJwt(null);
            empLoginLog.setCostTime(end-begin);
            empLoginlogMapper.save(empLoginLog);
            throw new TliasException("用户名或密码错误");
        }
    }
}
